﻿using System;
using System.Data;
using Newtonsoft.Json;

namespace UFIDA.U9.WSS.ProxyService.Json
{
    /// <summary>
    ///     DataTable转换器
    ///     1、保留字段名
    /// </summary>
    public class DataTableConverter : Newtonsoft.Json.Converters.DataTableConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            DataTable table = (DataTable) value;
            //DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
            writer.WriteStartArray();
            foreach (DataRow row in table.Rows)
            {
                writer.WriteStartObject();
                foreach (DataColumn column in row.Table.Columns)
                {
                    if (serializer.NullValueHandling == NullValueHandling.Ignore &&
                        (row[column] == null || row[column] == DBNull.Value))
                        continue;
                    //writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(column.ColumnName) : column.ColumnName);
                    writer.WritePropertyName(column.ColumnName);
                    serializer.Serialize(writer, row[column]);
                }

                writer.WriteEndObject();
            }

            writer.WriteEndArray();
        }
    }
}